<template>
  <iframe
    :src="iframeRouter"
    width="100%"
    frameborder="0"
    ref="iframeDom"
    class="iframe"
    :class="{ isLoad: isLoad }"
    v-if="foreignID"
  ></iframe>
  <div v-else>题组ID不存在</div>
</template>

<script>
import { location_QuestionBank, debounce, location } from "@/util/tool";
import { Session } from '@/util/storage/session.js'
import { mapState } from "vuex";
export default {
  data() {
    return {
      isLoad: false,
      height: 150,
    };
  },
  props: {
    iframeRouter: String,
    foreignID: Number,
    creativeCourse: Boolean
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    getCurrGuidelineData() {
      // 在找到的任务组中通过当前任务的任务编号找到任务
      let thistaskNoInGroup = this.getLocalStorageTaskData({taskID: this.$parent.taskID});
      if (!thistaskNoInGroup) return undefined;
      thistaskNoInGroup.taskGroupID = this.$parent.taskGroupID;
      return thistaskNoInGroup;
    },
    getIframeHeight() {
      return this.$refs.iframeDom?.clientHeight || 0;
    },
  },
  watch: {
    getIframeHeight(n) {},
  },
  methods: {
    handleClose() {
      this.$emit("handleIframeClose");
    },
    /**
     * @description 监听iframe加载完成
     */
    listenIframeOnload() {
      const that = this;
      const iframe = this.$refs.iframeDom;
      // 处理兼容行问题
      if (iframe.attachEvent) {
        iframe.attachEvent("onload", function () {
          that.isLoad = true;
          that.sendData(iframe);
          that.completeLoad = true;
        });
      } else {
        iframe.onload = function () {
          that.isLoad = true;
          that.sendData(iframe);
          that.completeLoad = true;
        };
      }
    },
    /**
     * otherWindow.postMessage(message, targetOrigin, [transfer]);
     * https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage
     * @description 向iframe发送消息
     */
    async sendData(dom) {
      let userInfoCookie = null;
      const res = await Session.get('userInfo', true)
      userInfoCookie = res;
      if (!userInfoCookie)
        return this.$antdMessage.error({
          content: "身份信息已过期！",
        });
      this.isLoad = false;
      let params = Object.assign({
        cookie: null,
        userInfo: this.userInfo,
        isStudy: true,
        taskDetail: this.creativeCourse ? { guidelineResults: {} } : this.getCurrGuidelineData,
        currGuidelineID: this.$parent.guidelineObj.guidelineID,
        iframeID: +new Date() + "" || "defaultIframeID",
      });
      dom.contentWindow.postMessage(
        JSON.stringify(params),
        location_QuestionBank(window)
      );
      // dom.contentWindow.postMessage(
      //   JSON.stringify(params),
      //   "http://localhost:3000"
      // );
      window.addEventListener(
        "message",
        (event) => {
          // Do we trust the sender of this message?  (might be
          // different from what we originally opened, for example).
          if (
            event.origin !== location(window) &&
            event.origin !== "http://localhost:3000"
          )
            return;
          const data = JSON.parse(event?.data);
          if (data.iframeID == params.iframeID) {
            // let iframeHeight = data?.iframeHeight;
            // this.height = iframeHeight;
            if (data.score && data.session_id) {
              this.$emit(
                "handleUpdateTaskScore",
                data.score,
                dom,
                params,
                data.session_id
              );
              return;
            }
            if (data.session_id) {
              this.$emit("handleUpdateSessionID", data.session_id, dom, params);
            }
          }
          // this.debounce(iframeHeight);
        },
        false
      );
    },
    debounce: debounce(function (e) {
      this.height = e;
    }, 100),
    getLocalStorageTaskData(data) {
      const { currNo } = this.$route.query;
      let myStudyData = localStorage.getItem("studyData")
        ? JSON.parse(localStorage.getItem("studyData"))
        : {};
      let getCurrStudyData = myStudyData[currNo][this.userInfo.userID];
      let currTaskData = getCurrStudyData.find(
        (item) => item.taskID == data.taskID
      );
      return currTaskData;
    },
  },
  mounted() {
    if (this.foreignID) this.listenIframeOnload();
  },
};
</script>

<style lang="stylus" scoped>
.iframe {
  max-width: 779px;
  height: 80vh;
}

.isLoad {
  height: 100%;
}
</style>